/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.util.xml;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/*
 *
 * */

/**
 *@author Alejandro Riveros Cruz Riveros Cruz
 *@version LoadXML.java,v 1 2008/20/03
 * */
public class XMLSAX extends DefaultHandler {

    /**
     *
     */
    private TableDocument xml;
    /**
     *
     */
    private String tempContent;

    /**
     * @param:
     * @return:
     */
    public XMLSAX() {
    }

    /**
     * 
     * @param path
     * @return
     */
    public TableDocument parseDocument(String path) {
        if (path.lastIndexOf("\\") == 0) {
            xml = new TableDocument(new String(path.substring(path.lastIndexOf("/") + 1, path.length())));
        } else {
            xml = new TableDocument(new String(path.substring(path.lastIndexOf("\\") + 1, path.length())));
        }
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(path, this);
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
        return xml;
    }

    /**
     * @param:
     * @return:
     */
    @Override
    public void startDocument() {
        // System.out.print("Starting parsing " + xml.getName() + " ...");
    }

    /**
     * @param:
     * @return:
     */
    @Override
    public void endDocument() {
        // System.out.println("finish.");
    }

    /**
     * @param:
     * @return:
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    }

    /**
     * @param:
     * @return:
     */
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        xml.addTagContent(qName, tempContent);
    }

    /**
     * @param:
     * @return:
     */
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        tempContent = String.valueOf(ch).substring(start, start + length);
    }
}
